//
//  OAuthViewController.swift
//  ShangHaiWeiBo
//
//  Created by 蔡杰 on 16/2/26.
//  Copyright © 2016年 蔡杰. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    override func loadView() {
        super.loadView()
        view = webView
        //设置导航栏
        title = "微博新浪登陆"
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "取消",
            style: UIBarButtonItemStyle.Plain,
            target: self,
            action: "didClickCancl")
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "自动填充",
            style: UIBarButtonItemStyle.Plain,
            target: self,
            action: "didClickAutoFill")
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.whiteColor()
        
        webView.loadRequest(NSURLRequest(URL: AFNworkTools.sharedTools.oauthURL))
        webView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
       
    }
    

    @objc private func didClickCancl(){
    
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    @objc private func didClickAutoFill(){
    
        //自动填装
        let js = "document.getElementById('userId').value='18267733865';" +
        "document.getElementById('passwd').value='cai111212011412';"
        
        // 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    deinit {
    
      print("已经销毁")
    }
  

}
extension OAuthViewController : UIWebViewDelegate{

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //当返回的地址和回调地址相同时返回true，不是则继续加载
       if let urlstring = request.URL?.absoluteString
        where !urlstring.hasPrefix(AFNworkTools.sharedTools.redirectUri){
        
            return true
        }
        //否则判断回调参数，如果授权成功 URL 的`查询字符串`中包含 code 参数
        guard let query = request.URL?.query where query.hasPrefix("code=") else {
        
            dismissViewControllerAnimated(true, completion: nil)
            return false
        }
        print("请求字符串 " + query)
        //获得请求码
        let code = query.substringFromIndex("code=".endIndex)
        print("请求码 = \(code)")
       //获得授权回调
        AFNworkTools.sharedTools.loadAccsessToken(code) { (result) -> () in
            
            
            guard let result = result else {
            
                print("网络不给力")
                return
            }
            UserAccount.sharedUserAccount.updateUserAccount(result)
            //创建通知观察者，实现控制访客视图和普通控制器跳转
            NSNotificationCenter.defaultCenter().postNotificationName(CZWeiBoLoginSuccessedNotification, object: nil)
            self.didClickCancl()
            print(result)
        }
        
       return false
    }
    
    
    
}
